package com.pwser.utils;

import com.pwser.pojo.JDGood;
import com.sun.istack.internal.NotNull;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class JDHtmlParseUtil {
    private static final String JD_SEARCH_URL = "https://search.jd.com/Search";
    private static final int JD_SEARCH_TIMEOUT = 300000;
    private static final String JD_GOODS_ELEMENT_ID = "J_goodsList";
    private static final String JD_GOODS_LIST_TAG = "li";
    private static final String JD_GOOD_IMG_TAG = "img";
    private static final String JD_GOOD_IMG_ATTR = "data-lazy-img";
    private static final String JD_GOOD_PRICE_CLASS = "p-price";
    private static final String JD_GOOD_TITLE_CLASS = "p-name";

    public static List<JDGood> getJDSearchContentByKeyword(@NotNull String keyword) throws IOException {
        // Document就是浏览器的DOM对象
        Document document = Jsoup.parse(new URL(JD_SEARCH_URL + "?keyword=" + URLEncoder.encode(keyword, "UTF-8")), JD_SEARCH_TIMEOUT);
        Element goodsElement = document.getElementById(JD_GOODS_ELEMENT_ID);
        Elements goodsLiElements = goodsElement.getElementsByTag(JD_GOODS_LIST_TAG);
        List<JDGood> jdGoodsList = new ArrayList<>();
        for (Element el : goodsLiElements) {
            String img = el.getElementsByTag(JD_GOOD_IMG_TAG).eq(0).attr(JD_GOOD_IMG_ATTR);
            Float price = Float.parseFloat(el.getElementsByClass(JD_GOOD_PRICE_CLASS).eq(0).text()
                            .split(" ")[0]
                            .replace("￥", ""));
            String title = el.getElementsByClass(JD_GOOD_TITLE_CLASS).eq(0).text();

            JDGood jdGood = new JDGood();
            jdGood.setTitle(title);
            jdGood.setPrice(price);
            jdGood.setImg(img);
            jdGoodsList.add(jdGood);
        }
        return jdGoodsList;
    }

    public static void main(String[] args) {
        try {
           JDHtmlParseUtil.getJDSearchContentByKeyword("java").forEach(
                   System.out::println
           );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
